package github.ziwukun.jsonql.orm;

import com.fasterxml.jackson.annotation.JsonAlias;

/**
 * 关系表链接模型
 * @author Hugo.Yu
 */
class RltPropBuilder {
	// 作为外部模型的属性名称
	@JsonAlias({"prop","propName"})
	String propName;
	// 是否是单一数量 是否只有一个
	@JsonAlias({"one","single"})
	boolean single = true;
	
	// 外键名，内部属性
	@JsonAlias({"foreign-field","foreignField"})
	String foreignField;
	// 主键名，模型的id外键名
	@JsonAlias({"primary-field","primaryField"})
	String primaryField;
	// 关系容器名
	@JsonAlias({"relation-container","rltCtnName"})
	String rltCtnName;
	// 关系容器类型
	@JsonAlias({"type","rltCtnType"})
	ContainerType rltCtnType;
	
	// 模型定义
	@JsonAlias({"model"})
	ModelBuilder model;
	
	RltPropImpl toRltProp(ModelImpl ofModel) {
		return new RltPropImpl(this,ofModel);
	}
	
	ContainerImpl instanceRltCtn() {
		return new ContainerImpl(this);
	}
	
	public static void instanceRltProp(RltPropBuilder builder,RltPropImpl rltProp,
		ModelImpl ofModel) {
		OrmAssert.notBlank(builder.propName, "属性名称不能为空");
		
		rltProp.propName = builder.propName;
		rltProp.single = builder.single;
		rltProp.ofModel = ofModel;
		rltProp.rltCtn = builder.instanceRltCtn();
		rltProp.foreignField = (CtnFieldImpl) rltProp.rltCtn.
			getFieldByName(builder.foreignField);
		rltProp.primaryField = (CtnFieldImpl)rltProp.rltCtn.
			getFieldByName(builder.primaryField);
		rltProp.propModel = builder.model.toModel();
	}
	
	public static void instanceRlfCtn(RltPropBuilder rltPropBuilder,
		ContainerImpl ctn) {
		
		OrmAssert.notBlank(rltPropBuilder.foreignField, "外键不能为空");
		OrmAssert.notBlank(rltPropBuilder.primaryField, "主键名称不能为空");
		OrmAssert.notBlank(rltPropBuilder.rltCtnName, "容器名称不能为空");
		OrmAssert.notBlank(rltPropBuilder.rltCtnType, "容器类型不能为空");
		
		ctn.ctnName = rltPropBuilder.rltCtnName;
		ctn.ctnType = rltPropBuilder.rltCtnType;
		ctn.fields.add(new CtnFieldImpl(rltPropBuilder.primaryField));
		ctn.fields.add(new CtnFieldImpl(rltPropBuilder.foreignField));
	}
}
